import beginWork from './ReactFiberBeginWork';
import completeWork from './ReactFiberCompleteWork';
import commitWorker from './ReactFiberCommitWork';
import scheduleCallback from '../scheduler/Scheduler';
let wip = null;
let wipRoot = null;

export default function ReactFiberWorkLoop(fiber) {
  wip = fiber;
  wipRoot = fiber;
  // requestIdleCallback(workLoop);
  scheduleCallback(workloop);
}

// function workLoop(deadline) {
//   while (wip && deadline.timeRemaining() > 0) {
//     performUnitOfWork();
//   }

//   if (!wip) {
//     commitRoot();
//   }
// }

function workloop(time) {
  while (wip) {
    if (time < 0) return false;
    performUnitOfWork(); // 该方法负责处理一个 fiber 节点
  }
  if (!wip && wipRoot) {
    commitRoot();
  }
}

function performUnitOfWork() {
  beginWork(wip);

  if (wip.child) {
    wip = wip.child;
    return;
  }

  completeWork(wip);

  let next = wip;
  while (next) {
    if (next.sibling) {
      wip = next.sibling;
      return;
    }

    next = next.return;

    completeWork(next);
  }

  wip = null;
}

function commitRoot() {
  commitWorker(wipRoot);
  wipRoot = null;
}
